<template>
	<view class="container">
		<view class="head">
			<text>共{{ total }}件</text>
			<view @click="delCart" class="del center" hover-class="hover">
				<image src="@/static/image/del.png" class="icon" />
				<text>删除</text>
			</view>
		</view>
		<list reqUrl="/api/carlist" formatData :handleFormat="handleFormat" ref="listInstance"
			emptyImg="/static/image/cart-empty.png" :immediatecheck="false">
			<template v-slot="{ list }">
				<view class="goods" v-for="(item, index) in list" :key="item.car_id">
					<checkbox @click="checkboxChange(index)" :checked="item.checked" :value="index" class="check_box"
						:class="{check:item.checked}" :color="primaryColor" />
					<view class="rightContent">
						<goods image_width="92px" image_height="92px" :name="item.goods_title" :sub_name="item.sku_name"
							:image="imgHost + item.pic" @click="toGoodsDetail(item.goods_id)">
							<template #bottom>
								<view class="bottom_c">
									<view class="origin_price">￥{{ item.original_price }}</view>
									<view class="bottom_bar">
										<view class="price">
											<view class="now_price">
												<text>￥</text>
												<text class="num">{{ item._integer }}</text>
												<text>.{{ item._decimal }}</text>
											</view>
										</view>
										<uni-number-box @change="onNumChange(item)" v-model="item.buy_num" :min="1"
											:max="item.stock" @click.stop class="stepper" />
									</view>
								</view>
							</template>
						</goods>
						<view v-if="item.delivery!==0" class="deliveryMethodTip">*仅支持{{['','快递','自提'][item.delivery]}}
						</view>
					</view>
				</view>
			</template>
			<template #emptyTip>
				<view class="cart_empty">
					<view class="text" hover-class="hover">
						<text>您的购物车空空如也，</text>
						<text @click="goProduct" class="special">去看看~</text>
					</view>
				</view>
			</template>
		</list>
	</view>
	<view class="fixed_bar">
		<view class="main">
			<view @click="onHandleCheckAll" class="left" hover-class="hover">
				<radio :checked="checkedAll" class="radio_check_all" :color="primaryColor" @click="onHandleCheckAll" />
				<view class="label">全选</view>
			</view>
			<view class="middle">
				<text>合计：</text>
				<text class="icon special">￥</text>
				<text class="num special">{{totalPrice}}</text>
			</view>
			<button @click="submit" :loading="submitLoading" :disabled="submitDisabled"
				:class="{disabled :submitDisabled}" class="button" type="primary"
				size="mini">{{submitLoading?'':'购买'}}</button>
		</view>
		<view class="env"></view>
	</view>
	<tabbar :active="2"></tabbar>
</template>

<script setup>
	import { ref, nextTick } from 'vue';
	import { debounce, sleep } from '@/utils/common/index';
	import request from '@/utils/common/request/index';
	import { onShow, onReachBottom } from '@dcloudio/uni-app';
	import { useCacheStore } from '@/store/modules/useCacheStore';
	import tabbar from '@/components/tabbar/tabBar.vue';
	import { useGetThemColor } from '@/hooks/useGetThemColor';


	const { primaryColor, secondaryColor } = useGetThemColor();
	const { imgHost } = getApp().globalData;

	onShow(() => {
		nextTick(async () => {
			totalPrice.value = 0;
			checkedAll.value = false;
			submitDisabled.value = true;
			submitLoading.value = false;
			// #ifdef H5
			await sleep(10);
			// #endif
			listInstance.value.resetRequest();
		})
	})
	// * 页面触底事件，不能删除，否则不能触发list组件触底事件
	onReachBottom(() => {});

	// * 获取购物车列表
	let total = ref(0);
	const listInstance = ref(null);
	const handleFormat = (res) => {
		total.value = res.total;
		/**产品数据格式化函数 */
		let data = res.data;
		data.forEach((item) => {
			[item._integer, item._decimal] = item.present_price.split('.');
			item.checked = false;
		})
		return data;
	}

	// * 数量加减
	const onNumChange = debounce(item => {
		nextTick(() => {
			let reqData = {
				goods_id: item.goods_id,
				sku_key: item.sku_key === undefined ? item.goods_id : item.sku_key,
				buy_num: item.buy_num
			}
			request({
				url: '/api/addcar',
				method: 'POST',
				data: reqData
			})
			checkDisabledAndComputePriceAndIsCheckAll();
		});
	});


	// * 选中、非选中、全选
	let checkedAll = ref(false); //全选
	let submitLoading = ref(false);
	let submitDisabled = ref(true);
	let totalPrice = ref(0);
	const checkboxChange = (index) => {
		let list = listInstance.value.captureList();
		list[index].checked = !list[index].checked;
		checkDisabledAndComputePriceAndIsCheckAll();
	}
	const onHandleCheckAll = () => {
		let list = listInstance.value.captureList();
		checkedAll.value = !checkedAll.value;
		if (list.length === 0) return uni.showToast({
			title: '请添加商品',
			icon: 'none'
		});
		list.forEach(item => {
			item.checked = checkedAll.value;
		});
		checkDisabledAndComputePriceAndIsCheckAll();
	};
	const checkDisabledAndComputePriceAndIsCheckAll = () => {
		let list = listInstance.value.captureList();
		let disabled = true;
		let price = 0;
		let checkAll = true;
		list.forEach(item => {
			if (item.checked) {
				disabled = false;
				price = Number((Number((item.present_price * item.buy_num).toFixed(2)) + price).toFixed((
					2)));
			} else {
				checkAll = false;
			}
		})
		if (list.length === 0) checkAll = false;
		submitDisabled.value = disabled;
		totalPrice.value = price;
		checkedAll.value = checkAll;
	};

	// * 删除购物车
	const delCart = () => {
		let list = listInstance.value.captureList();
		const checkedArr = list.map(item => {
			if (item.checked) return item.car_id;
		}).filter(item => item);
		if (checkedArr.length === 0) return uni.showToast({
			title: '请选择商品',
			icon: 'none'
		});
		uni.showModal({
			title: '提示',
			content: '确定执行此操作？',
			confirmColor: primaryColor.value,
			success(res) {
				if (res.cancel) return;
				request({
					url: '/api/delcar',
					method: 'POST',
					data: { car_id: checkedArr }
				}).then(() => {
					checkedArr.forEach(item => {
						const index = list.findIndex(goods => goods.car_id === item)
						list.splice(index, 1);
					})
					checkDisabledAndComputePriceAndIsCheckAll();
					let nowList = listInstance.value.captureList();
					total.value = nowList.length;
				})
			}
		})
	}

	// * 提交订单
	const submit = () => {
		submitLoading.value = true;
		let list = listInstance.value.captureList();
		let goods = [];

		let firstDeliveryMethod = 0; //配送方式0不限1仅支持快递2仅支持自提
		try {
			list.forEach(item => {
				if (!item.checked) return;

				if (item.buy_num === 0) {
					uni.showToast({
						title: `${item.goods_title}库存不足`,
						icon: 'none'
					})
					throw new Error('');
				}

				if (firstDeliveryMethod === 0 && item.delivery !== 0) firstDeliveryMethod = item.delivery;
				if (firstDeliveryMethod && item.delivery !== firstDeliveryMethod) {
					uni.showToast({
						title: `${item.goods_title}仅支持${['','快递','自提'][item.delivery]}`,
						icon: 'none'
					})
					throw new Error('');
				}

				goods.push({
					goods_id: item.goods_id,
					sku_key: item.sku_key === undefined ? item.goods_id : item.sku_key,
					buy_num: item.buy_num
				})
			})
		} catch (e) {
			submitLoading.value = false;
			return;
		}

		request({
			url: '/api/nyzf',
			method: 'POST',
			data: { goods }
		}).then(data => {
			data.enableDeliveryMethod = firstDeliveryMethod;
			const cacheStore = useCacheStore();
			cacheStore.setStorageData({
				data: data,
				field: 'odrerStorage',
			})
			uni.navigateTo({
				url: `/pages/settlement/settlement`,
			});
		}).finally(() => {
			submitLoading.value = false
		})
	};

	// * 前往商品详情
	const toGoodsDetail = (id) => {
		uni.navigateTo({
			url: `/pages/productDetail/productDetail?id=${id}`,
		});
	};

	// * 购物车为空时前往浏览产品
	const goProduct = () => {
		uni.switchTab({
			url: "/pages/product/product"
		})
	};
</script>


<style lang="scss" scoped>
	.container {
		&::after {
			content: '';
			display: block;
			padding-top: 80px;
		}
	}

	.head {
		display: flex;
		justify-content: space-between;
		padding: 14px 0;

		.del {
			color: #999;

			.icon {
				margin-right: 2px;
				width: 12px;
				height: 14px;
			}
		}
	}

	.goods {
		display: flex;
		align-items: center;
		padding: 10px;
		border-radius: 10px;
		background-color: #fff;

		&+.goods {
			margin-top: 10px;
		}

		.check_box {
			transform: scale(0.9);
			padding-right: 5px;
		}

		.check {

			::v-deep .uni-checkbox-input,
			::v-deep .uni-checkbox-input:hover {
				border-color: v-bind(primaryColor) !important;
			}

		}

		::v-deep .uni-checkbox-input {
			border-radius: 50% !important;
		}

		::v-deep .uni-checkbox-input:hover {
			border-color: #d1d1d1 !important;
		}

		.rightContent {
			flex: 1;
		}

		.deliveryMethodTip {
			margin-top: 8px;
			color: #878787;
			font-size: 12px;
		}

		.bottom_c {
			height: 100%;
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
		}

		.origin_price {
			text-decoration: line-through;
			font-size: 12px;
			color: #999;
		}

		.bottom_bar {
			display: flex;
			justify-content: space-between;
			align-items: flex-end;

			.price {
				flex: 1;
				display: flex;
				align-items: center;
			}

			.now_price {
				font-size: 12px;
				font-weight: bold;
				color: v-bind(secondaryColor);

				.num {
					font-size: 16px;
				}
			}

			.stepper {
				transform: scale(1.1);
			}
		}
	}

	.cart_empty {
		margin: 0 auto;
		width: 250px;

		.text {
			text-align: center;
			color: #999;
		}

		.special {
			color: v-bind(secondaryColor);
		}
	}

	.fixed_bar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 56px;
		padding: 10px;
		background-color: #fff;
		z-index: 9;

		.main {
			display: flex;
			align-items: center;
		}

		.left {
			display: flex;
			align-items: center;

			.radio_check_all {
				transform: scale(0.9);
			}

			::v-deep .uni-radio-input:hover {
				border-color: #d1d1d1 !important;
			}
		}

		.middle {
			flex: 1;
			text-align: right;
			padding: 0 30px;

			.special {
				color: v-bind(secondaryColor);
				font-weight: 500;
			}

			.icon {
				font-size: 10px;
			}

			.num {
				font-size: 20px;
			}
		}

		.button {
			width: 140rpx;
			height: 60rpx !important;
			line-height: 60rpx !important;
			border-radius: 40rpx;
			background-color: v-bind(primaryColor);

			&.disabled {
				opacity: .5;
			}
		}
	}
</style>
<style>
	/*只能在这里设置*/
	page {
		background-color: #f5f5f5;
	}
</style>